package com.qf.realm;

import com.qf.pojo.SysUsers;

import com.qf.service.MenuService;
import com.qf.service.RoleService;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author YDW
 * projectName:project2202_3
 * time:2022/5/15 17:22
 * description:
 */
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;



    //提供授权信息（权限信息）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //要强转转换为哪个对象，关键是在认证时存储到session中的对象类型
        SysUsers user = (SysUsers) principalCollection.getPrimaryPrincipal();

        //查询角色
        Set<String> roles=roleService.findRoles(user.getId());
        //查询权限
        Set<String> perms=menuService.findPerms(user.getId());

        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();

        //需要角色信息
        authorizationInfo.setRoles(roles);

        //需要权限信息
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;

    }

    //提供认证信息（账号和密码）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //在token对象中，username是字符串类型，直接强转
        String username = (String) authenticationToken.getPrincipal();
        //在tonken对象中 password是char[]，必须转换为char数组，再转换为string类型
        String password = new String((char[])authenticationToken.getCredentials());

        //根据用户名， 查询数据库，获取用户信息
        SysUsers user = userService.findByUsername(username);
        //与用户输入的账号和密码进行比较，如果没有问题，登录成功
        //用户是否存在
        if (user == null) {
            throw new UnknownAccountException("未知用户名");
        }
        //用户是否被锁定
        if(user.getStatus()==0){
            throw new LockedAccountException("用户已锁定");
        }
        //如果密码不相同，密码有误
        if (!password.equals(user.getPassword())){
            throw  new CredentialsException("密码输入有误");
        }
        //参数1：存储在session中的对象 ，密码对象，真实姓名
        AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(user,password,user.getRealname());
        return authenticationInfo;
    }
}
